﻿using PKTools;
using PKTools.Database;
using PKTools.Scheduler;
using System;
using System.Diagnostics;
using System.Linq;

namespace Scheduler
{
    partial class Job : IJob
    {
        public bool Schedule(DateTime currentTime)
        {
            if (!this.Active)
                throw new Exception("job is not active");

            using (new DisposeExecutor(() => 
            {
                var
                    jobHistory = new JobHistory
                        {
                            JobID = this.ID,
                            JobState = 2    // scheduled
                        };

                Sql.Context.Insert(jobHistory);

                this.LastJobHistoryID = jobHistory.ID;
                Sql.Context.Update(this);
            }))
            {
                this.NEET = this.JobSchedule.Schedule.NextExecution(this.LEET, currentTime);

                if (this.NEET < currentTime)
                    this.NEET = currentTime;

                Log.Entry(LogSeverity.Info, "LEET {0}, NEET {1}", this.LEET.ToDetailString(), this.NEET.ToDetailString());

                if (this.StopOn != null && this.NEET > this.StopOn)
                {
                    this.Active = false;
                    return false;
                }

                return true;
            }
         }

        public IJobStep GetFirstStep()
        {
            Debug.Assert(this.JobStepList.Count > 0);

            return this.JobStepList.OrderBy(e => e.Sequence).First();
        }

        public void Stop()
        {
            this.Active = false;
            Sql.Context.Update(this);

            this.JobHistory_LastJobHistoryID.JobState = 8;  // stoped on error
            Sql.Context.Update(this.JobHistory_LastJobHistoryID);
        }

        public void BeforeExecution(DateTime currentTime)
        {
            this.LEET = this.NEET;
            this.LET = currentTime;
            Sql.Context.Update(this);
        }


        public void Finalize(Exception ex)
        {
            this.JobHistory_LastJobHistoryID.JobState = 4;  // completed
            Sql.Context.Update(this);
        }
    }
}
